/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.game.message.generaor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.dom4j.DocumentException;

import com.game.message.generaor.Paragraph.ProtocolInfo;

/**
 * 
 * @author Elvin
 */
public class ClientProtocolsGenerator
{
	private String descriptionFile = null;
	private String generatedFile = null;

	private String packageName = "com.game.message.protocol";
	private String className = "ProtocolsConfig";
	private String baseClassName = "Protocols";
	private String variableType = "final public static int";
	private List<Paragraph> paragraphCollection = null;

	public ClientProtocolsGenerator(String descriptionFile, String generatedFile)
	{
		this.descriptionFile = descriptionFile;
		this.generatedFile = generatedFile;
	}

	public void generateFile() throws DocumentException, IOException
	{
		ProtocolParser protocolParser = new ProtocolParser(descriptionFile);
		this.paragraphCollection = protocolParser.parseFile();

		FileWriter fileWriter = new FileWriter(this.generatedFile, false);
		BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

		bufferedWriter.write("//This file is generated by program. Do not edit it manually.");
		bufferedWriter.newLine();
		bufferedWriter.newLine();
		bufferedWriter.write("package " + this.packageName + ";");
		bufferedWriter.newLine();
		bufferedWriter.write("import com.game.message.generaor.ProtocolConfigAnnotation;");
		bufferedWriter.newLine();
		bufferedWriter.newLine();

		bufferedWriter.write("public class " + this.className);
		if (null != this.baseClassName)
		{
			bufferedWriter.write(" extends " + this.baseClassName);
		}
		bufferedWriter.newLine();
		bufferedWriter.write("{");
		bufferedWriter.newLine();

		StringBuilder sb = new StringBuilder();
		sb.append("delete from alert_message;\n");
		for (Paragraph paragraph : this.paragraphCollection)
		{
			long protocolID = paragraph.getProtocolStartID();
			bufferedWriter.write("\t//" + paragraph.getDescription());
			bufferedWriter.newLine();
			for (ProtocolInfo protocol : paragraph.getProtocols())
			{
				if (protocol.getProtocolClass() != null)
				{
					bufferedWriter.write("\t" + " @ProtocolConfigAnnotation(protocolClass = " + protocol.getProtocolClass() + ".class"
					        + ", needLogin = " + protocol.isNeedLogin() + ")");
					bufferedWriter.newLine();
				}
				bufferedWriter.write("\t" + this.variableType + " " + protocol.getProtocolName() + " = 0x" + Long.toHexString(protocolID) + ";");
				bufferedWriter.newLine();

				long resultSuccessStartIndex = 1;
				long resultFailureStartIndex = 16;

				for (int tempIndex = 0; tempIndex < protocol.getResultNames().size(); ++tempIndex)
				{
					Result result = protocol.getResultNames().get(tempIndex);
					String resultName = result.getName();
					boolean isSuccess = result.isSuccess();
					String descName = protocol.getDescNames().get(tempIndex);
					// if (tempIndex == 0)
					// {
					// System.out
					// .println(String.format(
					// "\t\t<!-- %s -->",
					// protocol.getProtocolComment() != null ? protocol
					// .getProtocolComment() : ""));
					// }
					// System.out.println(String.format(
					// "\t\t<String name=\"%s\">%s</String>", resultName,
					// descName != null ? descName : ""));
					//

					System.out.println("insert into alert_message (id,`description`) values ('" + result.getName() + "','" + descName
					        + "') ON DUPLICATE KEY UPDATE `description` ='" + descName + "';");
//					sb.append("replace into alert_message (`code`,`id`,`description`) values ( '"+  + result.getName() + "','" + descName + "');\r\n");

					// System.out.println("update alert_message set id = '"+result.getName()+"', describe='"+descName+"';");

					if (isSuccess)
					{
						bufferedWriter.write("\t\t" + this.variableType + " " + resultName + " = 0x"
						        + Long.toHexString(protocolID + (resultSuccessStartIndex << 20)) + ";");
						sb.append("replace into alert_message (`code`,`id`,`description`) values ( '"+ (protocolID + (resultSuccessStartIndex << 20)) + "','" + result.getName() + "','" + descName + "');\r\n");
						++resultSuccessStartIndex;
					}
					else
					{
						bufferedWriter.write("\t\t" + this.variableType + " " + resultName + " = 0x"
						        + Long.toHexString(protocolID + (resultFailureStartIndex << 20)) + ";");
						sb.append("replace into alert_message (`code`,`id`,`description`) values ( '"+ (protocolID + (resultFailureStartIndex << 20)) + "','" + result.getName() + "','" + descName + "');\r\n");
						++resultFailureStartIndex;
					}
					bufferedWriter.newLine();
				}

				++protocolID;
			}
			bufferedWriter.newLine();
		}

		// 写文件
		File file = new File(System.getProperty("user.dir") + "/resources/output.sql");
		if (!file.exists())
		{
			boolean flag = file.createNewFile();
			if (!flag)
			{
				System.out.println("----error: create file error");
			}
		}
		BufferedWriter bufwrt = new BufferedWriter(new FileWriter(file));
		bufwrt.write(sb.toString());
		bufwrt.close();

		bufferedWriter.write("}");
		bufferedWriter.newLine();

		bufferedWriter.close();
	}
}
